﻿using CRM.Models;
using CRM.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace CRM.Controllers.Customer
{
    [Route("api/[controller]")]
    [ApiController]
    public class FollowController : BaseController
    {

        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> _userManager;

        public FollowController(MyDbContext dbContext, UserManager<User> userManager)
        {
            _dbContext = dbContext;
            _userManager = userManager;
        }
        [HttpGet("List/{id}")]
        public async Task<ResultStruct> List(int Id)
        {
            if (Id <= 0)
            {
                return Error(new object(), "参数错误");
            }
            var user = await _userManager.GetUserAsync(User);

            var List = await _dbContext.CustomerFollow
                .Where(m => m.CustomerId == Id && m.OemId == user.OemId)
                .Include(m => m.User)
                .OrderByDescending(m => m.Id)
                .ToListAsync();
            return Success(List);
        }


        [HttpGet("{id}")]
        public async Task<ResultStruct> Get(int id)
        {
            var user = await _userManager.GetUserAsync(User);
            var row = await _dbContext.CustomerFollow.Where(m => m.Id == id && m.OemId == user.OemId).FirstOrDefaultAsync();
            return row == null ? Error(new object(), "获取失败") : Success(row, "获取成功");
        }

        [HttpPost(nameof(Create))]
        public async Task<ResultStruct> Create(CustomerFollow follow)
        {
            var user = await _userManager.GetUserAsync(User);

            var CustomerId = follow.CustomerId;

            var Customer = await _dbContext.Customer.Where(m => m.Id == CustomerId && m.OemId == user.OemId).FirstOrDefaultAsync();

            if (Customer == null)
            {
                return Error(new object(), "客户不存在");
            }


            var Time = DateTime.Now;
            follow.UpdatedAt = Time;
            follow.UserId = user.Id;
            follow.CreatedAt = Time;
            follow.OemId = user.OemId;
            follow.CompanyId = user.CompanyId;
            follow.GroupId = user.GroupId;

            Customer.FollowAt = Time;
            Customer.UpdatedAt = Time;
            Customer.FollowMessage = follow.Content;

            var Transaction = _dbContext.Database.BeginTransaction();

            try
            {
                _dbContext.CustomerFollow.Add(follow);
                await _dbContext.SaveChangesAsync();
                Transaction.Commit();
            }
            catch (Exception e)
            {
                Transaction.Rollback();
                return Error(new object(), e.Message);
            }

            return Success(new object(), "创建成功");

        }
        [HttpPut("{id}")]
        public async Task<ResultStruct> Update(CustomerFollow follow)
        {
            var user = await _userManager.GetUserAsync(User);

            if (follow.Id <= 0)
            {
                return Error(new object(), "参数错误");
            }
            var row = await _dbContext.CustomerFollow.Where(m => m.Id == follow.Id && m.OemId == user.OemId).FirstOrDefaultAsync();

            if (row == null)
            {
                return Error(new object(), "数据不存在");
            }

            var Time = DateTime.Now;
            row.UpdatedAt = Time;
            row.Type = follow.Type;
            row.Content = follow.Content;
            row.NextAt = follow.NextAt;

            var status = await _dbContext.SaveChangesAsync();
            if (status == 1)
            {
                return Success(new object(), "更新成功");

            }
            return Error(new object(), "更新失败");
        }

        [HttpDelete("{id}")]
        public async Task<ResultStruct> Delete(int id)
        {
            var user = await _userManager.GetUserAsync(User);

            var row = await _dbContext.CustomerFollow.Where(m => m.Id == id && m.OemId == user.OemId).FirstOrDefaultAsync();
            if (row == null)
            {
                return Error(new object(), "数据不存在");
            }

            CustomerFollow.TypeEnum Enum = (CustomerFollow.TypeEnum)row.Type;
            var Content = $"删除客户跟进记录 跟进方式为{Enum}，跟进内容为{row.Content}";

            var transaction = _dbContext.Database.BeginTransaction();

            try
            {
                _dbContext.Remove(row);
                await _dbContext.SaveChangesAsync();
                await (new OperationLogService(_dbContext, HttpContext, _userManager)).AddLogAsync(new CustomerOperationLog()
                {
                    CustomerId = row.CustomerId,
                    Content = Content,
                });
                transaction.Commit();
            }
            catch (Exception e)
            {
                return Error(new object(), e.Message);
            }
            return Success(new object(), "删除成功");
        }
    }
}
